public class App {
    public static void main(String[] args) throws Exception {
        ListNode l1=genNodeFromNumber(249+"");
        ListNode l2=genNodeFromNumber(5649+"");
        addTwoNumbers(l1,l2);
    }

    public void reverseString(char[] s) {
        for(var i=0;i<s.length/2;i++){
            char ex=s[i];
            s[i]=s[s.length-1-i];
            s[s.length-1-i]=ex;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        var l1Str=new StringBuilder();
        l1Str.append(l1.val);
        while (l1.next!=null){
            l1=l1.next;
            l1Str.append(l1.val);
        }
        var l2Str=new StringBuilder();
        l2Str.append(l2.val);
        while (l2.next!=null){
            l2=l2.next;
            l2Str.append(l2.val);
        }
        StringBuilder shorter=l1Str.length()<=l2Str.length()?l1Str:l2Str;
        StringBuilder bigger=l1Str.length()>l2Str.length()?l1Str:l2Str;
        StringBuilder resultStr=new StringBuilder();
        var i=shorter.length()-1;
        var j=bigger.length()-1;
        var extraNum=0;
        while (i>=0){
            int cuur=Integer.parseInt(shorter.charAt(i)+"")+Integer.parseInt(bigger.charAt(j)+"")+extraNum;
            if((cuur+"").length()>1){
                resultStr.append((cuur+"").charAt(1));
                extraNum=1;
            }else {
                resultStr.append(cuur);
            }
            i--;
            j--;
        }
        if(bigger.length()>shorter.length()){
            i=bigger.length()-1-shorter.length();
            for(;i>=0;i--){
                if(extraNum==0){
                    resultStr.append(bigger.charAt(i));
                }else {
                    int curr=Integer.parseInt(bigger.charAt(i)+"")+extraNum;
                    if((curr+"").length()>1){
                        resultStr.append((curr+"").charAt(1));
                        extraNum=1;
                        if(i==0&&extraNum==1){
                            resultStr.append(1);
                        }
                    }else {
                        resultStr.append(curr);
                    }
                }
            }
        }
        System.out.println(resultStr.toString());
        var resultNode=genNodeFromNumber(resultStr.reverse().toString());
        return resultNode;
    }

    private static ListNode genNodeFromNumber(String s){
        var resultNode=new ListNode(Integer.parseInt(s.charAt(s.length()-1)+""));
        ListNode currNode=resultNode;
        for (var i=s.length()-2;i>=0;i--){
            var newNode=new ListNode(Integer.parseInt(s.charAt(i)+""));
            currNode.next=newNode;
            currNode=newNode;
        }
        return resultNode;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
